# coding:utf-8
import hashlib
import os

from AutoWool.main.utils.log_utils import Log


class FileUtils:

    def __init__(self):
        pass

    @staticmethod
    def file_exist(file_abs_path) -> bool:
        return os.path.exists(file_abs_path)

    @staticmethod
    def get_md5(file_abs_path) -> str:
        if not os.path.exists(file_abs_path):
            Log.error('FileUtils get_md5 ' + file_abs_path + ' not exist')
        md5obj = hashlib.md5()
        maxbuf = 8192
        f = open(file_abs_path, 'rb')
        while True:
            buf = f.read(maxbuf)
            if not buf:
                break
            md5obj.update(buf)
        f.close()
        hash = md5obj.hexdigest()
        return str(hash).upper()

    # 获取视频上传时间，粗略估算，假设上传速度为 10kb/s
    @staticmethod
    def get_file_upload_duration_second(videoPath) -> int:  # 返回 s
        return int(FileUtils.get_file_size_k(videoPath) / 10)

    # 获取文件大小（MB）
    @staticmethod
    def get_file_size_m(videoPath) -> int:
        file_byte = os.path.getsize(videoPath)
        return file_byte / (1024 ** 2)

    # 获取文件大小（KB）
    @staticmethod
    def get_file_size_k(video_path) -> int:
        file_byte = os.path.getsize(video_path)
        return file_byte / 1024

    # E:\\test.mp4  -> test.mp4
    @staticmethod
    def get_file_base_name(abs_path) -> str:
        return os.path.basename(abs_path)

    # E:\\test.mp4  -> mp4
    @staticmethod
    def get_file_back_fix(abs_path) -> str:
        return FileUtils.get_file_base_name(abs_path).split(".")[-1]

    # E:\\test.mp4  -> test
    @staticmethod
    def get_file_name_no_fix(abs_path) -> str:
        return FileUtils.get_file_base_name(abs_path).split(".")[0]

    @staticmethod
    def rename_file(abs_file_path, target_name):
        os.rename(abs_file_path, target_name)

    @staticmethod
    def delete_file(abs_file_path):
        os.remove(abs_file_path)

    @staticmethod
    def delete_fils(abs_file_path, prefix):
        files = os.listdir(abs_file_path)  # 得到文件夹下的所有文件名称
        for file in files:  # 遍历文件夹
            if file.find(prefix) != -1:
                file_abs_path = os.path.join(abs_file_path, file)
                os.remove(file_abs_path)
